package com.canyou.system.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.canyou.system.mapper.LoginInfoMapper;
import com.canyou.system.model.LoginInfo;
import com.canyou.system.service.LoginInfoService;
import com.canyou.utils.AddressUtils;
import com.canyou.utils.IpUtils;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author canyou
 * @since 2019-05-14
 */
@Service
public class LoginInfoServiceImpl extends ServiceImpl<LoginInfoMapper, LoginInfo> implements LoginInfoService {

    @Override
    public IPage<LoginInfo> getLoginInfoPage(IPage<LoginInfo> loginInfoPage, LoginInfo loginInfo) {
        return baseMapper.getLoginInfoPage(loginInfoPage, loginInfo);
    }

    @Async
    @Override
    public void saveLoginInfo(HttpServletRequest request, int status, String msg, String username) {
        final UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr(request);
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setLoginName(username);
        loginInfo.setIpAddr(ip);
        loginInfo.setLoginLocation(AddressUtils.getRealAddressByIp(ip));
        // 获取客户端操作系统
        String os = userAgent.getOperatingSystem().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();
        loginInfo.setBrowser(browser);
        loginInfo.setOs(os);
        loginInfo.setMsg(msg);
        loginInfo.setStatus(status);
        baseMapper.insert(loginInfo);
    }
}
